<template>
  <div class="app-container">
    <!-- 商家介绍 -->
    <el-card class="box-card">
      <h3>新增商家</h3>
      <el-form
        ref="business"
        :rules="rules"
        :model="business"
        label-width="150px"
      >
        <!-- <el-form-item label="商家编号" prop="businessId">
          <el-input v-model="business.businessId" />
        </el-form-item> -->
        <el-form-item label="商家名称" prop="businessName">
          <el-input v-model="business.businessName"/>
        </el-form-item>
        <el-form-item label="商家地址" prop="businessAddress">
          <el-input v-model="business.businessAddress"/>
        </el-form-item>
        <el-form-item label="费用设置">
          <el-row :gutter="1">
            <el-col :offset="0" :span="10">
              <el-form-item label="起送费" prop="startPrice">
                <el-input v-model="business.startPrice" placeholder="0.00">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="配送费" prop="deliveryPrice">
                <el-input v-model="business.deliveryPrice" placeholder="0.00">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="点餐类别">
          <el-select v-model="business.orderTypeId">
            <el-option
              v-for="(item, index) in orderTypes"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商家图片">
          <el-upload
            ref="upload"
            :action="uploadPath"
            :before-upload="handleChangeFile"
            :show-file-list="false"
            list-type="picture"
            :headers="headers"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
            :auto-upload="true"
            :multiple="true"
          >
            <img
              v-if="business.businessImg"
              :src="business.businessImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>

        <el-form-item label="商家备注">
          <el-input v-model="business.remarks"/>
        </el-form-item>

        <el-form-item label="商家介绍">
          <editor v-model="business.businessExplain"/>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 页面底部商家取消按钮 -->
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">新增</el-button>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import {addBusiness} from "@/api/business/business";
import {createStorage, uploadPath} from "@/api/system/storage";
import TinymceEditor from "@/components/TEditor.vue";
import {MessageBox} from "element-ui";
import {getToken} from "@/utils/auth";

export default {
  name: "BusinessCreate",
  components: {Editor: TinymceEditor},

  data() {
    return {
      fileList: [],
      orderTypes: [
        {label: "美食", value: 1},
        {label: "早餐", value: 2},
        {label: "跑腿代购", value: 3},
        {label: "汉堡披萨", value: 4},
        {label: "甜品饮品", value: 5},
        {label: "速食简餐", value: 6},
        {label: "地方小吃", value: 7},
        {label: "米粉面馆", value: 8},
        {label: "包子粥铺", value: 9},
        {label: "炸鸡炸串", value: 10},
      ],
      uploadPath: process.env.VUE_APP_TARGET_API + "/upload", // 文件上传路径
      business: {businessImg: ""}, // 商家信息
      // 验证规则
      rules: {
        businessAddress: [
          {required: true, message: "商家地址不能为空", trigger: "blur"},
        ],
        businessName: [
          {required: true, message: "商家名称不能为空", trigger: "blur"},
        ],
      },
      // 富文本编辑器初始化
      /* editorInit: {
        language: "zh_CN", // 汉化
        language_url: "/static/tinymce/langs/zh_CN.js", // 这里的地址指向 public 目录下的路径
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure("上传失败，请重新上传");
            });
        },
      } */
    };
  },
  computed: {
    // 上传文件请求头添加Token
    headers() {
      return {
        "Shopping-Admin-Token": getToken(),
      };
    },
  },
  created() {
    // 页面数据初始化
    this.init();
  },

  methods: {
    handleChangeFile(file, fileList) {
      if (!file) return;
      // suffix：后缀名 ，如：hello.jpg
      var suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const limit = file.size / 1024 / 1024 < 1;
      if (suffix !== "jpg" && suffix !== "png" && suffix !== "bmp") {
        this.$refs.upload.clearFiles();
        this.$message({
          message: "上传文件只能是 .jpg、.png、bmp格式!",
          type: "warning",
        });
        return false;
      }
      if (!limit) {
        this.$refs.upload.clearFiles();
        this.$message({
          message: "上传文件大小必须小于1MB!",
          type: "warning",
        });
        return false;
      }
    },
    // 获取数据
    init: function () {
      /* listCatAndBrand().then((response) => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      }); */
    },

    // 取消商家上架钩子
    handleCancel: function () {
      this.$router.push({path: "/business/index"});
    },
    // 上架商家 钩子
    handlePublish: function () {
      // 调用接口
      addBusiness(this.business)
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: response.msg,
          });
          this.$router.push({path: "/business/index"});
        })
        .catch((response) => {
          MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
            confirmButtonText: "确定",
            type: "error",
          });
        });
    },

    // 商家图片上传
    uploadPicUrl: function (response) {
      let fm = process.env.VUE_APP_IMAGE_SHOW_FORM;
      console.log("----新增商家：fm:" + fm);
      if ("db" == fm) {
        this.business.businessImg = response.data.url;
      } else if ("file" == fm) {
        this.business.businessImg =
          process.env.VUE_APP_TARGET_API + response.data.url;
      }
    }
  }
};
</script>
